package com.anrongtec.zcpt.tab01;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.base.BaseFragment;
import com.anrongtec.zcpt.callback.StoreStringCallBack;
import com.anrongtec.zcpt.interfaces.HttpUtil;
import com.anrongtec.zcpt.interfaces.module.JsonDataRestult;
import com.anrongtec.zcpt.interfaces.module.PageList;
import com.anrongtec.zcpt.module.AppModel;
import com.anrongtec.zcpt.tab04.DividerGridItemDecoration;
import com.anrongtec.zcpt.util.GsonUtil;
import com.anrongtec.zcpt.util.LogUtil;
import com.anrongtec.zcpt.util.Util;
import com.art.base.util.ApkUtils;
import com.art.base.util.ToastShow;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter.OnItemClickListener;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;
import com.zhy.adapter.recyclerview.wrapper.LoadMoreWrapper;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 我的应用
 *
 * @author cxy
 */
public class TabFirstFragment extends BaseFragment implements OnClickListener {

    private RecyclerView rv;

    private WebView webView;

    private TextView tv_button;
    private SwipeRefreshLayout swipe_refresh;
    private CommonAdapter<AppModel> adapter;
    //	private List<FunctionModel> functions;
    private List<AppModel> apps= new ArrayList<>();
    private List<AppModel> newApps=new ArrayList<>();
    private List<String> appsList;
    private AppModel tempApp;
    private TextView tv_header;
    private EmptyWrapper empty;
    private LoadMoreWrapper loadMoreWrapper;
    private static final int SPAN_COUNT = 4;
    private List datas;//获取本地安装应用与商店存在应用相同 的应用信息

    private boolean isGetAppsInfo = true;//是否正在获取app信息

    private TextView tv_num;
    private final static int GET_APPS_FROM_SERVER = 2;//从服务器获取本地安装与商店相同的数据

    private Animation in, out;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    empty.setEmptyView(R.layout.empty_view);
                    rv.setAdapter(empty);
                    if (apps != null) {
                        Log.e("11111111",""+apps.size());
                        apps.clear();
                    }
                    else{
                        apps = new ArrayList<>();
                    }
//                    apps.addAll((List<AppModel>) msg.obj);
                    Log.e("333333333",""+newApps.size());
                    apps.addAll(newApps);
                    empty.notifyDataSetChanged();
                    if (swipe_refresh != null && swipe_refresh.isRefreshing()) {
                        swipe_refresh.setRefreshing(false);
                    }
                    break;
                case GET_APPS_FROM_SERVER:
                    getAppsInfoFromServer();
                    break;
                case 3:
                    ToastShow.shortMessage(getActivity(), "暂无安装应用app");
                    break;
                default:
                    break;
            }

            tv_num.setText("我的应用共" + apps.size() + "款");

        }
    };
    // 从服务器获取本地安装与商店相同的数据
    private void getAppsInfoFromServer() {
        if (appsList.size() <= 0) {
            return;
        }
        final String requestJson = GsonUtil.toTypeQueryApps(appsList);
        HttpUtil.post(requestJson, new StoreStringCallBack(getActivity()) {
            @Override
            public void onResponse(boolean arg0, String json, Request arg2, Response arg3) {
                super.onResponse(arg0, json, arg2, arg3);
//                LogUtil.e("商店相同的返回数据" + json);
                JsonDataRestult<PageList<AppModel>> result = GsonUtil.decode(json,
                        new TypeToken<JsonDataRestult<PageList<AppModel>>>() {
                        }.getType());
                if (newApps != null) {
                    newApps.clear();
                } else {
                    newApps = new ArrayList<>();
                }
                if (result != null && result.getData() != null && result.getData().getApps()!=null&& result.getData().getApps().size() !=0) {

//                    LogUtil.e("商店相同的返回解析数据" + result.getData().getApps().toString());
//                    LogUtil.e("商店相同的返回解析数据" + result.getData().getApps().size());
                    for (int i = 0; i < result.getData().getApps().size(); i++) {
                        AppModel appModel = result.getData().getApps().get(i);
                        newApps.add(appModel);
                    }
                    for (int i=0;i<newApps.size();i++){
                        if(newApps.get(i).getAppPackName().equals("com.anrongvs")){
                            newApps.remove(i);
                        }
                    }
                    handler.handleMessage(handler.obtainMessage(1,newApps));
                } else {
                    handler.handleMessage(handler.obtainMessage(1));
                    ToastShow.shortMessage(getActivity(), "暂无安装应用app");
                }
            }

            @Override
            public void onError(boolean isFromCache, Call call, Response response, Exception e) {
                super.onError(isFromCache, call, response, e);
                LogUtil.e(e.toString());
            }

        });
    }

    /**
     * 展示数据的url
     */
//	private String url;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        initData();
        View v = inflater.inflate(R.layout.fragment_tab_first, null);
        initViews(v);
        return v;
    }


    public void refresh() {

        getAppsInfo();
    }

    /**
     * 初始化数据
     */
    @Override
    protected void initData() {
        apps = new ArrayList<>();
        newApps = new ArrayList<>();
        appsList = new ArrayList<>();
//        getAppsInfo();
        refresh();
    }

    /**
     * 初始化控件
     */
    @Override
    protected void initViews(View view) {
        tv_num = (TextView) view.findViewById(R.id.tv_tab01_num);

        tv_button = (TextView) view.findViewById(R.id.tv_tab01_button);
        tv_button.setVisibility(View.GONE);
        tv_button.setOnClickListener(this);

        initRecyclerView(view);
        initSwipeRefresh(view);
    }

    /**
     * 初始化下拉刷新
     *
     * @param view
     */
    private void initSwipeRefresh(View view) {
        swipe_refresh = (SwipeRefreshLayout) view.findViewById(R.id.swipe_tab01_refresh);
        swipe_refresh.setEnabled(false);
        swipe_refresh.setColorSchemeResources(
                android.R.color.holo_blue_bright,
                android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        swipe_refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipe_refresh.setRefreshing(true);
                getAppsInfo();
            }
        });
    }


    /**
     * 初始化recyclerview
     *
     * @param view
     */
    private void initRecyclerView(View view) {
        rv = (RecyclerView) view.findViewById(R.id.tab01_recyclerview);
        rv.addItemDecoration(new DividerGridItemDecoration(getActivity()));
        rv.setLayoutManager(new GridLayoutManager(getContext(), SPAN_COUNT, GridLayoutManager.VERTICAL, false));

        adapter = new CommonAdapter<AppModel>(getContext(), R.layout.item_tab_first, apps) {
            @Override
            protected void convert(ViewHolder holder, AppModel t, int position) {
                    ImageView iv = holder.getView(R.id.iv_tab01_item);
                    ImageLoader.getInstance().displayImage(t.getIconUrl(), iv);
                    if(t.getAppPackName().equals("com.anrongvs")){
                        holder.setText(R.id.tv_tab01_item, "ocr扫描");
                    }else{
                        holder.setText(R.id.tv_tab01_item, t.getAppName());
                    }


            }
        };

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder,
                                    int position) {
                Log.e("posion",position+"");
                if (apps.get(position).getActivity() == null||apps.get(position).getActivity().equals("")) {
                    ApkUtils.openAPP(getContext(), apps.get(position).getAppPackName());
                } else {
                    com.anrong.sdk.util.log.LogUtil.trace(Log.ERROR, "22222", apps.get(position).getActivity());

                    ApkUtils.openAPP(getContext(), apps.get(position).getAppPackName(),
                            apps.get(position).getActivity());
                    // ApkUtils.openDefaultApp(getActivity(),apps.get(position).getAppPackName());
                }
               /* AppModel appModel = apps.get(position);
                if (ApkUtils.isInstalled(getActivity(), appModel.getAppPackName(), appModel.getLocalVersionCode())) {
                    ApkUtils.openAPP(getContext(), appModel.getAppPackName());
                } else {
                    ToastShow.shortMessage(getActivity(), "未发现该应用，请下载");
                }*/
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder,
                                           int position) {
                // TODO Auto-generated method stub
                return false;
            }
        });

        empty = new EmptyWrapper(adapter);
        empty.setEmptyView(R.layout.loading_view);

//		loadMoreWrapper = new LoadMoreWrapper(empty);
//		loadMoreWrapper.setLoadMoreView(R.layout.default_loading);
//		loadMoreWrapper.setOnLoadMoreListener(new OnLoadMoreListener() {
//			@Override
//			public void onLoadMoreRequested() {
//				if (isGetAppsInfo) {
//					return;
//				}
//				apps.addAll(apps);
//				handler.sendEmptyMessageDelayed(1, 3000);
//			}
//		});

        rv.setAdapter(empty);
    }

    @Override
    protected void initEvents(View view) {

    }


    private void multiDexThread(){
        for (int i = 0; i < 10; i++) {
            getAppsInfo();
        }
    }

    /**
     * 获取非系统应用
     */
    public void getAppsInfo() {

//        Util.post(new Runnable() {
//            @Override
//            public void run() {
                if (appsList != null) {
                    appsList.clear();
                } else {
                    appsList = new ArrayList<>();
                }
                Log.e("appslist11111",""+appsList.size());
                appsList.addAll(Util.getAppsFromPhone(getActivity()));
                Log.e("appslist",""+appsList.size());
                Log.e("applistsize",""+Util.getAppsFromPhone(getActivity()).size());
                //从服务获取
                handler.sendEmptyMessage(GET_APPS_FROM_SERVER);
//            }
//        }
//        );
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_tab01_button:
                if (webView.getVisibility() == View.GONE) {
                    webView.startAnimation(in);
                    webView.setVisibility(View.VISIBLE);
                    tv_button.setText("我的应用");
                } else {
                    webView.startAnimation(out);
                    webView.setVisibility(View.GONE);
                    tv_button.setText("统计分析");
                }
                break;

            default:
                break;
        }
    }

 }
